package com.xjd.edu.admin.service;

import com.google.code.kaptcha.Producer;

import com.xjd.edu.common.admin.core.captcha.CaptchaProperties;
import com.xjd.edu.common.admin.core.constant.CacheConstants;
import com.xjd.edu.common.admin.core.exception.CaptchaException;
import com.xjd.edu.common.utils.Base64;
import com.xjd.edu.common.utils.UuidUtil;
import com.xjd.edu.toolkit.cache.GameRedisTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码实现处理
 *
 * @author ruoyi
 */
@Slf4j
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    //@Autowired
    //private RedisService redisService;

    @Autowired
    private GameRedisTemplate gameRedisTemplate;

    @Autowired
    private CaptchaProperties captchaProperties;

    /**
     * 生成验证码
     */
    @Override
    public Map<String, Object> createCaptcha() throws IOException, CaptchaException {
        Map<String, Object> captchaMap = new HashMap<String, Object>();
        boolean captchaEnabled = captchaProperties.getEnabled();
        captchaMap.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return captchaMap;
        }
        // 保存验证码信息
        String uuid = UuidUtil.uuid();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        String captchaType = captchaProperties.getType();
        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        gameRedisTemplate.set(verifyKey, code, Duration.ofMinutes(2));
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            log.error("图像严重码异常！" + e.getMessage());
            throw new CaptchaException("图像严重码异常！");
        }

        //String verifyCode = (String) gameRedisTemplate.get(verifyKey).orElse(null);
        captchaMap.put("uuid", uuid);
        captchaMap.put("img", Base64.encode(os.toByteArray()));
        return captchaMap;
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCaptcha(String code, String uuid) throws CaptchaException {
        if (StringUtils.isEmpty(code)) {
            throw new CaptchaException("验证码不能为空");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = (String) gameRedisTemplate.get(verifyKey).orElse(null);
        if (captcha == null) {
            throw new CaptchaException("验证码已失效");
        }
        gameRedisTemplate.del(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException("验证码错误");
        }
    }
}
